package org.sixtythousand.joker.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultLastHttpContent;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.IOException;

/**
 * @author zhoulk
 * @date 2023/10/19 11:19
 * @desc
 */
public class NettyServletOutputStream extends ServletOutputStream {

    protected NettyHttpChannel nettyHttpChannel;
    protected ChannelHandlerContext ctx;

    public NettyServletOutputStream(NettyHttpChannel nettyHttpChannel ) {
        this.nettyHttpChannel = nettyHttpChannel;
        this.ctx = nettyHttpChannel.getCtx();
    }


    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {

    }

    @Override
    public void write(int b) throws IOException {
     }

    @Override
    public void write(byte b[]) {

    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        // checkClosed();
        if (len == 0) {
            return;
        }

        ByteBuf ioByteBuf = ctx.alloc().ioBuffer(len);
        ioByteBuf.writeBytes(b, off, len);

        writeHttpBody(ioByteBuf, ioByteBuf.readableBytes());
    }


    protected void writeHttpBody(Object httpBody, long length) {
        try {
            // todo checkCLosed

            if (httpBody instanceof ByteBuf) {
                DefaultLastHttpContent httpContent = new DefaultLastHttpContent((ByteBuf) httpBody, false);
                ctx.write(httpContent);
            }

        } catch (Exception e) {

        }
    }

    @Override
    public void flush() {
        ctx.flush();
    }
}
